//
//  BSSingleChannelViewController.m
//  SuoSiApp
//
//  Created by 张明阳 on 16/4/21.
//  Copyright © 2016年 Ym. All rights reserved.
//

#import "ZipArchive.h"
#import "StringResponse.h"
#import "AsyncSocket.h"
#import "BSSingleChannelViewController.h"

@interface BSSingleChannelViewController ()<UIGestureRecognizerDelegate>
// 差值多少 代表1毫伏
@property (nonatomic, assign) NSInteger pointKK;
//定时器是否暂停
@property (nonatomic, assign) BOOL isSuspend;
//当前显示第几通道
@property (nonatomic, assign) int currentChanel;
@end

@implementation BSSingleChannelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _pointKK = 250;
    _drawingCountOnce = 7;
    _currentChanel = 2; //默认显示中间的
    //    计算下 满屏的宽度
    CGFloat height1 = self.currentSpeedLB.bottom + kMartin10;
    CGFloat kmm = 0;
    if (kScrenWidth > 380) {
        kmm = k6pmm;
    } else {
        kmm = k1mm;
    }
    //    三通道
    CGFloat height2 = kmm * 12 ;
    
    CGFloat height3 = kMartin10 + self.modeView.bottom - self.adjustSpeedLB.top;
    
    CGFloat height = height1 + height2 + height3;

    [super addScrollViewWithheight:height];
    [super addSubview];
    
    [self singleECGView];

     self.threeChannelLB.text = @"三通道";
    [self.threeeChannelBT setBackgroundImage:[UIImage imageNamed:@"xxszsbxx_27"] forState:(UIControlStateNormal)];
    [self.threeeChannelBT addTarget:self action:@selector(threeeChannel) forControlEvents:(UIControlEventTouchUpInside)];
    _drawTimer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(drawingpoint) userInfo:nil repeats:YES];
    [self adjustSpeed];
    [self selectChanel];
    [self setRSSIImage];
    
    self.speed10BT.selected = YES;
    self.MV1BT.selected = YES;
    
//    KVO 检测心率
    [self observeHeartRate];
    [self addTap];

}

- (void)adjustSpeed{
    [self.speed5BT addTarget:self action:@selector(speed5mm:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    [self.speed10BT addTarget:self action:@selector(speed10mm:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    [self.speed20BT addTarget:self action:@selector(speed20mm:) forControlEvents:(UIControlEventTouchUpInside)];



}
- (void)selectChanel{

    [self.MIIBT addTarget:self action:@selector(MII) forControlEvents:(UIControlEventTouchUpInside)];
    [self.MV1BT addTarget:self action:@selector(MV1) forControlEvents:(UIControlEventTouchUpInside)];

    [self.MV5BT addTarget:self action:@selector(MV5) forControlEvents:(UIControlEventTouchUpInside)];

}
- (void)MII{
    
    self.MV1BT.selected = NO;
    self.MV5BT.selected = NO;
    _currentChanel = 1;
}

- (void)MV1{
    
    self.MV5BT.selected = NO;
    self.MIIBT.selected = NO;
    _currentChanel = 2;

}
- (void)MV5{
    
    self.MIIBT.selected = NO;
    self.MV1BT.selected = NO;
    _currentChanel = 3;

}
- (void)singleECGView{
    
    CGFloat kmm = 0;
    if (kScrenWidth > 380) {
        kmm = k6pmm;
    } else {
        kmm = k1mm;
    }
    //    显示单通道的
    
    NSInteger n = ((self.adjustSpeedLB.top - kMartin10) - (self.currentSpeedLB.bottom + kMartin10))  / kmm;
    
    self.ecgView = [[TripleECGView alloc]initWithFrame:CGRectMake(kMartin10, self.currentSpeedLB.bottom + kMartin10, kScrenWidth - kMartin20, (12) * kmm )];
    
    self.ecgView.layer.cornerRadius = 8;
    //        显示区域 边框的颜色
    self.ecgView.layer.borderColor = [UIColor grayColor].CGColor ;
    //        显示框的宽度
    self.ecgView.layer.borderWidth = 1;
    self.ecgView.clipsToBounds = YES; //边缘内容省略
    [self.scrollView addSubview:self.ecgView];


}
- (void)viewWillAppear:(BOOL)animated{

    if (_drawTimer) {
        //关闭定时器
        [_drawTimer setFireDate:[NSDate distantPast]];
    }
    

}


- (void)viewDidDisappear:(BOOL)animated{

    if (_drawTimer) {
        //关闭定时器
        [_drawTimer setFireDate:[NSDate distantFuture]];
    }


}

- (void)drawingpoint{

    _tempArr = [[NSMutableArray alloc]init];
    [_tempArr removeAllObjects];
    
    [self.ecgView.pointArray removeAllObjects];
#pragma mark  判断需要接收的是第几通道的数据
    
    switch (_currentChanel) {
        case 1:
        {
            if ([BSBluetoothSingleton shareBlutooth].chanel1Arr != nil && [BSBluetoothSingleton shareBlutooth].chanel1Arr.count >= _drawingCountOnce) {
                //    判断数组里面还剩多少点 够不都画得了
                
                NSArray *arr = [[BSBluetoothSingleton shareBlutooth].chanel1Arr subarrayWithRange:NSMakeRange(0, _drawingCountOnce)];
                
                _tempArr = [NSMutableArray arrayWithArray:arr];
                
                [[BSBluetoothSingleton shareBlutooth].chanel1Arr removeObjectsInRange:NSMakeRange(0, _drawingCountOnce)];
            }

        }
            break;
        case 2:
        {
            if ([BSBluetoothSingleton shareBlutooth].chanel2Arr != nil && [BSBluetoothSingleton shareBlutooth].chanel2Arr.count >= _drawingCountOnce) {
                //    判断数组里面还剩多少点 够不都画得了
                
                NSArray *arr = [[BSBluetoothSingleton shareBlutooth].chanel2Arr subarrayWithRange:NSMakeRange(0, _drawingCountOnce)];
                
                _tempArr = [NSMutableArray arrayWithArray:arr];
                
                [[BSBluetoothSingleton shareBlutooth].chanel2Arr removeObjectsInRange:NSMakeRange(0, _drawingCountOnce)];
            }

        
        }
            break;
        case 3:
        {
            if ([BSBluetoothSingleton shareBlutooth].chanel3Arr != nil && [BSBluetoothSingleton shareBlutooth].chanel3Arr.count >= _drawingCountOnce) {
                //    判断数组里面还剩多少点 够不都画得了
                
                NSArray *arr = [[BSBluetoothSingleton shareBlutooth].chanel3Arr subarrayWithRange:NSMakeRange(0, _drawingCountOnce)];
                
                _tempArr = [NSMutableArray arrayWithArray:arr];
                
                [[BSBluetoothSingleton shareBlutooth].chanel3Arr removeObjectsInRange:NSMakeRange(0, _drawingCountOnce)];
            }

        }
            break;
            
        default:
            break;
    }

 
    if (_tempArr.count > 0) {
        self.ecgView.pointArray = _tempArr;
        [self.ecgView fireDrawing];
    } else {
        [self.ecgView keepDrawing];
    }
}
// 调节走纸速度
- (void)speed5mm:(UIButton *)sender{
    
    self.currentSpeedLB.text = @"当前速度: 5mm/mV 12.5mm/s ";
    self.ecgView.pointMartin = 0.6;
    
    if (sender.selected == NO) {
        sender.selected = !sender.selected;
        
    }
    self.ecgView.kkk = 2;
    self.speed10BT.selected = NO;
    self.speed20BT.selected = NO;
    
}
- (void)speed10mm:(UIButton *)sender{
    self.currentSpeedLB.text = @"当前速度: 10mm/mV 25mm/s ";
    self.ecgView.pointMartin = 1.2;
    if (sender.selected == NO) {
        sender.selected = !sender.selected;
        
    }
    self.ecgView.kkk = 1;
    NSLog(@"%d",sender.selected);
    self.speed5BT.selected = NO;
    self.speed20BT.selected = NO;
    
}

- (void)speed20mm:(UIButton *)sender{
    
    self.currentSpeedLB.text = @"当前速度: 20mm/mV 50mm/s ";

    self.ecgView.pointMartin = 2.4;
    
    self.ecgView.kkk = 0.5;
    
    if (sender.selected == NO) {
        sender.selected = !sender.selected;
        
    }    self.speed10BT.selected = NO;
    self.speed5BT.selected = NO;
    
}

#pragma mark  选择 显示通道数据




#pragma mark 批量上传的方法
- (void)updateBatch{
    
    
    //    管理文件
    NSFileManager *filemanager = [NSFileManager defaultManager];
    
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    NSString *path = @"/ECGData";
    
    NSString *filePath = [documents[0] stringByAppendingString:path];
    
    NSString *zipFile = [filePath stringByAppendingPathComponent:@"/20160510103203.zip"];
    BOOL isExist = [filemanager removeItemAtPath:zipFile error:nil];
    NSLog(@"%d",isExist);
    
    
    NSArray *listArrfile = [BSUserSGton getECGDataFileListFromPath:filePath];
    NSMutableArray *listArr = [NSMutableArray arrayWithArray:listArrfile];
    
    NSInteger countOffiles = listArrfile.count;
    
    
    NSString *user_id = [BSUserSGton userHandle].user_id;
    NSArray *arr = [[NSArray alloc]init];
    ZipArchive *za = [[ZipArchive alloc] init];
    [za CreateZipFile2:zipFile];
    //    [za addFileToZip:sourcePath5 newname:@"20160510103209.dat"];
    
    if (listArr == 0) {
        return;
    }
    
    if (listArr.count > 1) {
        arr = [listArr subarrayWithRange:NSMakeRange(0, 1)];
    }else{
        arr = listArr;
    }
    for (int i = 0; i < arr.count; i++) {
        
        NSString *ECGfile = [filePath stringByAppendingPathComponent:arr[i]];
        //        判断这个文件是否为空 为空 直接删除
        long  long int bytes = [[filemanager attributesOfItemAtPath:ECGfile error:nil] fileSize];
        NSLog(@"%lld",bytes);
        
        
        [za addFileToZip:ECGfile newname:arr[i]];
    }
    BOOL success = [za CloseZipFile2];
    NSLog(@"Zipped file with result %d",success);
    
    //    如果压缩成功 打包data  上传
    NSData *filedata = [NSData data];
    if (success) {
        
        NSURL *url2 = [NSURL fileURLWithPath:zipFile];
        
        filedata = [NSData dataWithContentsOfURL:url2];
        [filemanager removeItemAtPath:zipFile error:nil];
        
    }
    
    NSString *uuidStr = [BSBluetoothSingleton shareBlutooth].uuiduuid;
    
    [PKRequestManager ChangePwdWithnetUrl:NetStr upLoadWay:(NSString *)@"1" userID:user_id deviceID:(NSString *)uuidStr filenames:arr data:filedata method:POST finish:^(NSData *data) {
        //            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        //            NSLog(@"%@",dic);
        //            上传成功 删除 从listArr arr  本地删除arr的文件  修改显示
        StringResponse *model = [[StringResponse alloc]init];
        [model dealNoNoteWithData:data];
        if ([model.Code isEqualToString:@"0"]) {
            for (int i = 0; i < arr.count; i++) {
                
                NSString *ECGfile = [filePath stringByAppendingPathComponent:arr[i]];
                //        判断这个文件是否为空 为空 直接删除
                [filemanager removeItemAtPath:ECGfile error:nil];
                
                NSLog(@"上传成功");
                [listArr removeObject:arr[i]];
                //                _lableUploadNote.text = [NSString stringWithFormat:@"正在上传%u/%d个",_numberOffiles - (int)listArr.count,_numberOffiles];
                
                if (listArr.count == 0) {
                    //                    [_uploadButton setTitle:@"已完成" forState:(UIControlStateNormal)];
                    return;
                }
            }
            if (arr.count != 0) {
                [self updateBatch];
            }
            
        } else {
            [PKRequestManager showAlertView:model.Message];
            //            _isUploading = NO;
        }
    } error:^(NSError *error) {
        ;
    }];
    
}
//手势
- (void)addTap{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:nil];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
    
    
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    NSString *str =  NSStringFromClass([touch.view class]);
    //    NSLog(@"%@",NSStringFromClass([touch.view class]));
    if ([str isEqualToString:@"TripleECGView"]) {
        //控制定时器是否暂停
        if (_isSuspend == NO) {
            //            关闭定时器
            [_drawTimer setFireDate:[NSDate distantFuture]];
            _isSuspend = YES;
            
        } else {
            //            开启定时器
            [_drawTimer setFireDate:[NSDate distantPast]];
            _isSuspend = NO;
        }
    }
    return YES;
}


- (void)back{

    [self.navigationController popViewControllerAnimated:YES];
  

}

- (void)threeeChannel{

    [self.navigationController popViewControllerAnimated:YES];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
